package com.bilibili.juc.cf;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;

import java.util.Date;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

/**
 *  thenCompose 方法的作用是将第一个CompletableFuture的结果传递给第二个CompletableFuture。这两个CompletableFuture都是异步执行的
 *  但是只有当第一个CompletableFuture执行完成后，将值传递给第二个CompletableFuture时，它才会异步执行
 * @auther zzyy
 * @create 2022-01-17 18:59
 */
public class CompletableFutureComposeDemo
{
    public static void main(String[] args) {
        CompletableFuture<String> completableFuture1 = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName()+"\t -----查询用户的订单号 start " + DateUtil.format(new Date(), DatePattern.NORM_DATETIME_PATTERN));
            //暂停几秒钟线程
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+"\t -----查询用户的订单号 end " + DateUtil.format(new Date(), DatePattern.NORM_DATETIME_PATTERN));
            return "10";
        });

        CompletableFuture<String> result = completableFuture1.thenCompose(new Function<String, CompletionStage<String>>() {
            @Override
            public CompletionStage<String> apply(String value) {
                return CompletableFuture.supplyAsync(() -> {
                    System.out.println(Thread.currentThread().getName()+"\t -----根据用户的订单号查询用户ID start " + DateUtil.format(new Date(), DatePattern.NORM_DATETIME_PATTERN));
                    //暂停几秒钟线程
                    try {
                        TimeUnit.SECONDS.sleep(2);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName()+"\t -----根据用户的订单号查询用户ID end " + DateUtil.format(new Date(), DatePattern.NORM_DATETIME_PATTERN));
                    return "订单号为:"+value + " ,对应的用户ID为: 888" ;
                });
            }
        });

        System.out.println(result.join());

    }
}
